// pay-sdk.js
// 用于以 SDK 方式集成支付 iframe 的示例实现

export class PaySDK {
  constructor(options) {
    this.options = options;
    this.iframe = null;
    this.origin = options.iframeOrigin;
    this.token = options.token;
    // 公用获取订单和价格信息的方法
    this.getOrderInfo = () => (typeof window.oemGetCheckoutsInfo === 'function') ? (window.oemGetCheckoutsInfo() || {}) : {};
    this.getPriceDetail = () => (typeof window.order_price_detail !== 'undefined') ? (window.order_price_detail || {}) : {};
    this.orderInfo = this.getOrderInfo();
    this.priceDetail = this.getPriceDetail();
    this.onSuccess = options.onSuccess || function(){};
    this.onError = options.onError || function(){};
    this.onReady = options.onReady || function(){};
    this._messageHandler = this._messageHandler.bind(this);
    this._handlers = {
      PAYMENT_INIT: this._onPaymentInit.bind(this),
      GET_ORDER_INFO: this._onGetOrderInfo.bind(this),
      PAYMENT_RESULT: this._onPaymentResult.bind(this),
      RESIZE_HEIGHT: this._onResizeHeight.bind(this)
    };
  }

  mount(container) {
    if (!container) throw new Error('container 不能为空');
    this.iframe = document.createElement('iframe');
    this.iframe.src = this.options.iframeUrl;
    this.iframe.style.border = 'none';
    this.iframe.style.width = '100%';
    this.iframe.style.height = '500px';
    this.iframe.id = 'pay-sdk-iframe';
    container.appendChild(this.iframe);
    window.addEventListener('message', this._messageHandler);
  }

  destroy() {
    window.removeEventListener('message', this._messageHandler);
    if (this.iframe && this.iframe.parentNode) {
      this.iframe.parentNode.removeChild(this.iframe);
    }
    this.iframe = null;
  }

  start() {
    if (!this.iframe) throw new Error('iframe 未挂载');
    // 主动通知 iframe 初始化
    this.iframe.contentWindow.postMessage({ type: 'PAYMENT_INIT' }, this.origin);
  }

  _messageHandler(event) {
    if (event.origin !== this.origin) return;
    const { type } = event.data;
    if (type && this._handlers[type]) {
      this._handlers[type](event.data);
    }
  }

  sendMessage(message) {
    if (this.iframe && this.iframe.contentWindow) {
      // 每次发送都自动附带最新 orderInfo 和 priceDetail
      const orderInfo = this.getOrderInfo();
      const priceDetail = this.getPriceDetail();
      this.iframe.contentWindow.postMessage({
        ...message,
        orderInfo,
        priceDetail
      }, this.origin);
    }
  }

  _onPaymentInit() {
    this._beforePayment()
      .then(allow => {
        if (allow) {
          this.sendMessage({
            type: 'PAYMENT_START',
            token: this.token
          });
        } else {
          this.sendMessage({
            type: 'PAYMENT_DENY'
          });
        }
      })
      .catch(err => {
        this.sendMessage({
          type: 'PAYMENT_DENY',
          error: err.message
        });
      });
  }

  _onGetOrderInfo() {
    this.sendMessage({
      type: 'ORDER_INFO'
    });
  }

  _onPaymentResult(data) {
    if (data.success) {
      this.onSuccess(data);
    } else {
      this.onError(data);
    }
  }

  _onResizeHeight(data) {
    const { height } = data;
    if (height && typeof height === 'number' && height > 0) {
      this.iframe.style.height = height + 'px';
    }
  }

  async _beforePayment() {
    if (typeof window.oemBeforePayment === 'function') {
      const result = await window.oemBeforePayment();
      if (!result) return false;
    }
    if (typeof this.options.beforePayment === 'function') {
      return await this.options.beforePayment();
    }
    return true;
  }
}
